import { getToken } from "@/utils/auth";
import { Message } from "@arco-design/web-react";
import { modalInstance } from "@/components/GobalModal";
import axios from "axios";
import { useLocation, useNavigate } from "react-router-dom";
import store from "@/store";
import {
  clearFormRequestList,
  updateRequestList,
} from "@/store/modules/appSlice";

const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000, // request timeout
});

// 自定义配置
const customOptions = {
  repeat_request_cancel: false, // 是否开启取消重复请求, 默认为 true
};

service.interceptors.request.use(
  (config) => {
    customOptions.repeat_request_cancel &&
      store.dispatch(updateRequestList({ config }));
    const token = getToken();
    if (token) {
      config.headers["X-Token"] = token;
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    // store.dispatch(clearFormRequestList({ config: response.config }));
    // 处理文件流
    // if (!response.headers["content-type"].startsWith("application/json")) {
    //   return response;
    // }
    const res = response.data;

    // if the custom code is not 200, it is judged as an error.
    if (res.code !== 200) {
      Message.error(res.message || "Error");
      console.error("error", res.message || "Error");
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        const navigate = useNavigate();
        const location = useLocation();
        if (location.pathname !== "/login") {
          modalInstance?.confirm?.({
            title: "系统提示",
            content: "您已退出登录，您可以取消并停留在此页面或者重新登录",
            onCancel: () => {},
            onOk: () => {
              navigate("/login", { replace: true });
            },
            okText: "重新登录",
          });
        }
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res;
    }
  },
  (error) => {
    store.dispatch(clearFormRequestList({ config: error.config }));
    Message.error(error.message);
    return Promise.reject(error);
  }
);

export default service;
